<template>
<div class="full-height page-content content bg-white">
<!--  搜索区-->
  <collapse ref="collapse" class="collapse-content after">
    <template v-slot:content>
      <yz-condition-filter
        v-model="queryParams"
        @resetSearch="onResetSearch"
        @onSubmit="onSearch"
      >
        <select-tree label="部门"
                     :sel-tree="queryParams.location"
                     style="height: 50px;"
                     class="margin-r-20"
                     ref="selectTree"
                     :tree-list="locationOptions"
                     @treeChange="_changeTreeNode" />
                  <fuzzy-search
                    style="width: 260px;padding-left: 7px;margin-right: 20px"
                    v-model.trim="queryParams.people"
                    :fuzzyParams="fuzzyParams"
                    fuzzyNumber="keyword"
                    :isShowValue="false"
                    :fuzzyObj="['name', 'id']"
                    showAllOption
                    isFilter
                    title="人员"
                    :fuzzyFunc="getUserFilter"
                    @onSelect="getCurrentPeopleOption"
                  ></fuzzy-search>
        <div class=" font-size-16">
          <span class="form-name">日期:</span>
          <date-picker
            format="YYYY-MM-DD"
            :clearable="false" :editable="false"
            :type="dateType" v-model="dateRange"
            range placeholder="选择时间范围"
            style="width: 240px;margin-left: 5px"
          />
        </div>
      </yz-condition-filter>
      <div class="form-inline bottom">
        <q-btn-dropdown  outline
                         style="padding: 0px 5px"
                        :disable="!tableData.length"
                        color="primary" label="导出Excel">
          <q-list>
            <q-item clickable v-close-popup @click="showExcel = true">
              <q-item-section>
                <q-item-label>导出明细</q-item-label>
              </q-item-section>
            </q-item>
            <q-item clickable v-close-popup @click="exportExcel()">
              <q-item-section>
                <q-item-label>导出总表</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </div>
    </template>
  </collapse>
  <!--搜索区结束-->
  <!-- 图表的标题 -->
  <!-- 图表-->
  <q-table
    :data="tableData" :columns="tableColumns"
    row-key="id" class="scroll stick-last-col myTable"
    :pagination.sync="pagination" :hide-bottom="!!tableData.length"
    :loading="isTableLoading"
    color="primary"
  >
    <template v-slot:body-cell-name="props">
      <q-td>
        {{ props.row.name || '--'}}
      </q-td>
    </template>
    <template v-slot:body-cell-departmentName="props">
      <q-td>
        {{ props.row.departmentName || '--'}}
      </q-td>
    </template>
    <template v-slot:body-cell-operate="props">
      <q-td class="text-center" style="width: 50px">
        <table-btn btnType="other" icon="icontubiao-139" tooltip="详情" @click="showLogs(props.row)"/>
      </q-td>
    </template>
  </q-table>
  <yz-pagination v-model="pagination" @onSearch="getList"/>
  <!--  详情框-->
  <performance-detail
    ref="detail"
    :show="people.show"
    @close="people.show = false"
    :showItem="people.showItem"
    :showDate="people.date"
  />
  <downloadPeopleDefine :show-excel="showExcel"
                        @close="showExcel=false"
                        :excelParams="excelParams"
                        :columns="tableColumns"/>
</div>
</template>

<script>
import Collapse from 'src/components/collapse'
import SelectTree from 'src/components/select-tree'
import downloadPeopleDefine from './components/DownloadPeopleDefine'
import PerformanceDetail from './components/performance-detail'
import moment from 'moment'
import { getDepartmentsTree, getPerformanceReports, downloadPerformance } from '../../boot/statistics/performance'
import exportStat from './components/stat-export'
import { mapGetters } from 'vuex'
import { getUserFilter } from '../../boot/system/user-manage'
import _ from 'lodash'
export default {
  name: 'performance',
  components: {
    Collapse,
    PerformanceDetail,
    downloadPeopleDefine,
    SelectTree
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  data () {
    return {
      department: null,
      requestId: null, // 导出唯一标识
      dateType: 'date',
      dateRange: [moment(new Date()).subtract(7, 'days').toDate(), new Date()],
      queryParams: {
        location: { }, // 所在位置
        people: ''
      },
      locationOptions: [], // 所在位置数据源
      peopleOption: [{
        'label': '全部',
        'value': 'all'
      }], // 人员下拉数据
      peopleMap: {}, // 人员详细
      // 表格头部数据
      tableColumns: [
        { name: 'name', field: 'name', label: '员工姓名', align: 'left' },
        { name: 'departmentName', field: 'departmentName', label: '部门/班组', align: 'left' },
        { name: 'plannedQuantity', field: 'plannedQuantity', label: '计划数量', align: 'left' },
        { name: 'finishedQuantity', field: 'finishedQuantity', label: '完成数量', align: 'left' },
        { name: 'achievementRate', field: 'achievementRate', label: '数量达成率', align: 'left' },
        { name: 'pieceRateWage', field: 'pieceRateWage', label: '计件工资', align: 'left' },
        { name: 'plannedDuration', field: 'plannedDuration', label: '计划工时(h)', align: 'left' },
        { name: 'actualDuration', field: 'actualDuration', label: '实际工时(h)', align: 'left' },
        { name: 'timeWage', field: 'timeWage', label: '计时工资', align: 'left' },
        { name: 'restDuration', field: 'restDuration', label: '休息时长(分钟)', align: 'left' },
        // { name: 'timeAchievementRate', field: 'timeAchievementRate', label: '工时达成率', align: 'left' },
        { name: 'operate', field: 'operate', label: '操作', align: 'center' }
      ],
      // 表格内容
      tableData: [],
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      // 表格正在加载
      isTableLoading: false,
      // 详情
      people: {
        show: false,
        item: {}
      },
      isInit: true,
      operatorIds: [],
      excelParams: {},
      fuzzyParams: {
        pageNum: 1,
        pageSize: 100000,
        departmentId: '',
        searchBy: 'name'
      },
      showExcel: false,
      getUserFilter: getUserFilter
    }
  },
  created () {
    this.init()
  },
  methods: {
    getDuration (val) {
      return exportStat.getDuration(val)
    },
    // 导出Excel
    exportExcel () {
      let data = {
        excelHead: [],
        since: this.getDate(this.dateRange[0]),
        before: this.getDate(this.dateRange[1])
      }
      if (!this.queryParams.people) {
        this.departmentId = this.queryParams.location.id
        data = { ...data, departmentId: this.departmentId }
      } else {
        data = { ...data, operatorIds: [this.queryParams.people] }
      }
      this.tableColumns.forEach(item => {
        if (item.name !== 'operate') {
          data.excelHead.push({
            field: item.name,
            name: item.label
          })
        }
      })
      this.$q.loading.show()
      const params = [{ name: this.queryParams.people }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      downloadPerformance(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
        }
      }).catch(() => {
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getDate2(this.dateRange[0])}-${this.getDate2(this.dateRange[1])}${this.queryParams.location && this.queryParams.location.label}人员绩效报表.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    init () {
      this.getDepartment()
    },
    // 获取部门结构树
    getDepartment () {
      getDepartmentsTree().then(res => {
        // 重新组织 tree
        res.forEach(reorganize)
        function reorganize (node) {
          if (node.level === 5) {
            node.label = node.opname
          }
          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }
        this.locationOptions = res
        this.selectFirstLocation()
        this.getList()
      })
    },
    // 选择部门树节点 *
    _changeTreeNode: function (val) {
      this.queryParams.location.label = val.label
      this.fuzzyParams.departmentId = val.id
      this.queryParams.people = ''
      if (val.id && val.label) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
      }
    },
    // 选中第一个部门
    selectFirstLocation () {
      if (this.locationOptions.length === 0) {
        return
      }
      const first = this.locationOptions[0]
      this.queryParams.location.id = first.id
      this.fuzzyParams.departmentId = first.id
      this.queryParams.location.level = first.level
      this.queryParams.location.label = first.label
      this.$refs.selectTree.setValue(this.queryParams.location)
    },
    getCurrentPeopleOption (val, option) {
      this.peopleOption = option
    },
    // 搜索
    getList () {
      const since = this.getDate(this.dateRange[0])
      const before = this.getDate(this.dateRange[1])
      let params = {
        since: since,
        before: before,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize
      }
      if (!this.queryParams.people) {
        this.departmentId = this.queryParams.location.id
        params = { ...params, departmentId: this.departmentId }
      } else {
        params = { ...params, operatorIds: [this.queryParams.people] }
      }
      if (this.queryParams.location.id) {
        let operatorIds = []
        this.isTableLoading = true
        this.excelParams = _.cloneDeep(params)
        getPerformanceReports(params).then(res => {
          this.pagination.rowsNumber = res.data.total
          res.data.list.forEach((item) => {
            operatorIds.push(item.operatorId)
          })
          if (!res.data.list[0].departmentName) {
            res.data.list.forEach((item) => {
              item.departmentName = this.queryParams.location.label
            })
          }
          this.operatorIds = operatorIds
          this.tableData = res.data.list
        }).finally(() => {
          this.isTableLoading = false
        })
      } else {
        this.$message.warning('所选部门人员为空，请重新选择')
      }
    },
    // 获取时间
    getDate (val) {
      return moment(val).format('YYYY-MM-DD')
    },
    getDate2 (val) {
      return moment(val).format('YYYYMMDD')
    },
    // 详情弹出框
    showLogs (item) {
      this.$refs.detail.getPerformanceDetail(item, this.getDate(this.dateRange[0]), this.getDate(this.dateRange[1]))
      this.people.show = true
      this.people.showItem = item
      this.people.date = `${this.getDate(this.dateRange[0])}~${this.getDate(this.dateRange[1])}`
    },
    // 重置
    onResetSearch () {
      this.dateRange = [moment(new Date()).subtract(7, 'days').toDate(), new Date()]
      this.queryParams.people = ''
      this.selectFirstLocation()
    },
    // 搜索
    onSearch () {
      this.pagination.pageNum = 1
      this.getList()
    }
  }
}
</script>

<style scoped lang="stylus">
  .performance {
    >>>.q-field__marginal {
      font-size: 16px;
      color: #000;
      font-weight: 400;
      text-align: right;
    }
  }
</style>
